package com.rxt.thermopro.ui.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.SparseArray
import androidx.core.util.forEach
import androidx.core.util.isNotEmpty
import androidx.core.util.set
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.app.common.base.BaseFragment
import com.rxt.thermopro.R
import com.rxt.thermopro.app.AppContext
import com.rxt.thermopro.app.LocalDataDao
import com.rxt.thermopro.bean.EventAlarmTextData
import com.rxt.thermopro.bean.ProbeBean
import com.rxt.thermopro.bean.ProfileBean
import com.rxt.thermopro.viewmodel.BBQViewModel
import com.rxt.thermopro.viewmodel.BleMessageViewModel
import com.rxt.thermopro.viewmodel.BleMessageViewModel.Companion.DEVICE_TYPE_BBQ
import com.rxt.thermopro.viewmodel.BleMessageViewModel.Companion.DEVICE_TYPE_GRILL
import com.rxt.thermopro.viewmodel.DeviceStatusViewModel
import com.rxt.thermopro.viewmodel.EventViewModel
import kotlinx.android.synthetic.main.fragment_bbq.*
import kotlinx.android.synthetic.main.fragment_bbq.backButton
import kotlinx.android.synthetic.main.fragment_bbq.flow1
import kotlinx.android.synthetic.main.fragment_bbq.flow11
import kotlinx.android.synthetic.main.fragment_bbq.flow2
import kotlinx.android.synthetic.main.fragment_bbq.flow21
import kotlinx.android.synthetic.main.fragment_bbq.image1
import kotlinx.android.synthetic.main.fragment_bbq.image11
import kotlinx.android.synthetic.main.fragment_bbq.image2
import kotlinx.android.synthetic.main.fragment_bbq.image21
import kotlinx.android.synthetic.main.fragment_bbq.image3
import kotlinx.android.synthetic.main.fragment_bbq.image31
import kotlinx.android.synthetic.main.fragment_bbq.mainMenuButton
import kotlinx.android.synthetic.main.fragment_bbq.meatText
import kotlinx.android.synthetic.main.fragment_bbq.meatText1
import kotlinx.android.synthetic.main.fragment_bbq.targetLowNum
import kotlinx.android.synthetic.main.fragment_bbq.targetLowNum1
import kotlinx.android.synthetic.main.fragment_bbq.targetNum
import kotlinx.android.synthetic.main.fragment_bbq.targetNum1
import kotlinx.android.synthetic.main.fragment_bbq.textBlock1
import kotlinx.android.synthetic.main.fragment_bbq.textBlock2
import kotlinx.android.synthetic.main.fragment_bbq.textTarget
import kotlinx.android.synthetic.main.fragment_bbq.textTarget1
import kotlinx.android.synthetic.main.fragment_bbq.viewBluetoothBBQ
import kotlinx.android.synthetic.main.fragment_bbq.viewForecastTime
import kotlinx.android.synthetic.main.fragment_bbq.viewForecastTime1
import kotlinx.android.synthetic.main.fragment_bbq.viewNoData
import kotlinx.android.synthetic.main.fragment_bbq.viewNoData1
import kotlinx.android.synthetic.main.fragment_bbq.viewNum
import kotlinx.android.synthetic.main.fragment_bbq.viewNum1
import kotlinx.android.synthetic.main.fragment_bbq.viewPhoneBBQ
import kotlinx.android.synthetic.main.fragment_bbq.viewTime1
import kotlinx.android.synthetic.main.fragment_bbq.viewTime11
import kotlinx.android.synthetic.main.fragment_bbq.viewTrend1
import kotlinx.android.synthetic.main.fragment_bbq.viewTrend11
import kotlinx.android.synthetic.main.fragment_bbq.viewUnit
import kotlinx.android.synthetic.main.fragment_bbq.viewUnit1

class BBQFragment : BaseFragment<BBQViewModel>() {

    override fun layoutId(): Int {
        return R.layout.fragment_bbq
    }

    companion object {
        private const val ARG_DEVICE_NAME = "deviceName"
        private const val ARG_DEVICE_ADDRESS = "address"
        private const val ARG_DEVICE_PROBE_STATUS = "probeStatus"

        private const val TARGET_TEMP = 1
        private const val HIGH_LOW_TEMP = 2
        private const val TEMP_NONE = 3

        fun newInstance(deviceName: String, address: String): BBQFragment {
            return BBQFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_DEVICE_NAME, deviceName)
                    putString(ARG_DEVICE_ADDRESS, address)
                }
            }
        }
    }

    private var mData = ProbeBean()
    private lateinit var mDeviceStatusViewModel: DeviceStatusViewModel
    private lateinit var mBleViewModel: BleMessageViewModel
    private lateinit var mEventViewModel: EventViewModel
    private lateinit var profileArray: SparseArray<ProfileBean>
    private val probeArray = mutableListOf<ProbeBean>()
    private var firstTemp = -1
    private var deviceType = DEVICE_TYPE_BBQ

    private val refreshTempDataCache = mutableListOf<ProbeBean>()

    override fun onResume() {
        super.onResume()
        if (refreshTempDataCache.isNotEmpty()) {
            mBleViewModel.notifyMsgData.value =
            hashMapOf<Long, MutableList<ProbeBean>>().apply {
                this[System.currentTimeMillis()] = mutableListOf<ProbeBean>().apply {
                    this.addAll(refreshTempDataCache)
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun initView(savedInstanceState: Bundle?) {
        mDeviceStatusViewModel =
            ViewModelProvider(requireActivity()).get(DeviceStatusViewModel::class.java)
        mBleViewModel =
            ViewModelProvider(requireActivity()).get(BleMessageViewModel::class.java)
        mEventViewModel = ViewModelProvider(requireActivity()).get(EventViewModel::class.java)
        val deviceName = arguments?.getString(ARG_DEVICE_NAME, "") ?: ""
        val address = arguments?.getString(ARG_DEVICE_ADDRESS, "") ?: ""
        mData.address = address
        mData.name = deviceName

        if (mData.name.contains("grill", true)) {
            probeParent3.isVisible = false
            probeParent4.isVisible = false
            deviceType = DEVICE_TYPE_GRILL
            profileArray = SparseArray<ProfileBean>(2)
        } else {
            profileArray = SparseArray<ProfileBean>(4)
        }
        //信号 电量
        if (mBleViewModel.signalLevelCache.isNotEmpty() &&
            mBleViewModel.signalLevelCache.containsKey(mData.address)
        ) {
            val signal = mBleViewModel.signalLevelCache[mData.address] ?: -100
            setSignal(signal)
            viewBluetoothBBQ.isSelected = signal != -100
        }
        if (mBleViewModel.notifyInfoDataCache.isNotEmpty()) {
            setBatteryLevel(mBleViewModel.notifyInfoDataCache.last().second.electricity.toInt())
        }

//        mBleViewModel.connectSuccess.observeInFragment(this, Observer {
//            mViewModel.setProfile(profileArray,mData.address,deviceType)
//        })

        mDeviceStatusViewModel.initProfile(deviceType, mData.address)

        setListener()

        mBleViewModel.signalLevel.observeInFragment(this, Observer {
            if (it.values.last().containsKey(mData.address)) {
                println("=====>  setSignal $it")
                val signal = it.values.last()[mData.address] ?: -100
                setSignal(signal)
                viewBluetoothBBQ.isSelected = signal != -100
            }
        })

        mBleViewModel.signalLevelNoConnect.observeInFragment(this, Observer {
            if (it.values.last().containsKey(mData.address)) {
                println("=====>  setSignal  NoConnect $it")
                val signal = it.values.last()[mData.address] ?: -100
                viewBluetoothBBQ.isSelected = signal != -100
                viewPhoneBBQ.isSelected = signal != -100
            }
        })

        mBleViewModel.loadCacheData.observeInFragment(this, Observer {
            if (mBleViewModel.notifyInfoDataCache.isNotEmpty()) {
                setBatteryLevel(mBleViewModel.notifyInfoDataCache.last().second.electricity.toInt())
            }
            if (mBleViewModel.signalLevelCache.isNotEmpty() &&
                mBleViewModel.signalLevelCache.containsKey(mData.address)
            ) {
                val signal = mBleViewModel.signalLevelCache[mData.address] ?: -100
                setSignal(signal)
                viewBluetoothBBQ.isSelected = signal != -100
            }
            if (mBleViewModel.notifyMsgDataCache.containsKey(mData.address) &&
                mBleViewModel.notifyMsgDataCache[mData.address]?.isNotEmpty() == true
            ) {
                mBleViewModel.notifyMsgDataCache[mData.address]?.let { itList ->
                    updateTemp(itList)
                }
            }

            profileArray.forEach { key, profileBean ->
                if (profileBean.singleTemp && mBleViewModel.notifyMsgDataCache.isNotEmpty() &&
                    mBleViewModel.notifyMsgDataCache.containsKey(mData.address)
                ) {
                    when (key) {
                        0 -> {
                            mBleViewModel.notifyMsgDataCache[mData.address]?.get(0)?.let { item ->
//                                computeNeedTime(
//                                    0, item.temperatureNUm.toDouble(),
//                                    profileBean.highTemperatureNum.toDouble()
//                                )
                            }
                        }
                        1 -> {
                            mBleViewModel.notifyMsgDataCache[mData.address]?.get(1)?.let { item ->
//                                computeNeedTime(
//                                    1, item.temperatureNUm.toDouble(),
//                                    profileBean.highTemperatureNum.toDouble()
//                                )
                            }
                        }
                        2 -> {
                            mBleViewModel.notifyMsgDataCache[mData.address]?.get(2)?.let { item ->
//                                computeNeedTime(
//                                    2, item.temperatureNUm.toDouble(),
//                                    profileBean.highTemperatureNum.toDouble()
//                                )
                            }
                        }
                        3 -> {
                            mBleViewModel.notifyMsgDataCache[mData.address]?.get(3)?.let { item ->
//                                computeNeedTime(
//                                    3, item.temperatureNUm.toDouble(),
//                                    profileBean.highTemperatureNum.toDouble()
//                                )
                            }
                        }
                    }
                }
            }
        })

        mBleViewModel.notifyRefreshTempData.observeForever(Observer {
            if (it.last().address == mData.address) {
                refreshTempDataCache.clear()
                refreshTempDataCache.addAll(it)
            }
        })

        mBleViewModel.notifyMsgData.observeInFragment(this, Observer { item->
            val it=item.values.last()
            if (it.last().address == mData.address) {
                updateTemp(it)
            }
        })

        mBleViewModel.notifyInfoData.observeInFragment(this, Observer {
            if (it.address == mData.address) {
                mViewModel.setProfile(profileArray, mData.address, deviceType)
                println("======> setBatteryLevel  ${it.electricity}")
                setBatteryLevel(it.electricity.toInt())
            }
        })

        //断开连接
        mBleViewModel.disconnectData.observeInFragment(this, Observer {
            if (it.first == mData.address) {
                setBatteryLevel(-1)
                setSignal(-100)
                viewBluetoothBBQ.isSelected = false

                viewNoData.isVisible = true
                flow2.isInvisible = true
                viewNoData1.isVisible = true
                flow21.isInvisible = true
                viewNoData2.isVisible = true
                flow22.isInvisible = true
                viewNoData3.isVisible = true
                flow23.isInvisible = true
            }
        })

        mDeviceStatusViewModel.profileData1.observeInFragment(this, Observer { item ->
            if (item.containsKey(mData.address)) {
                item[mData.address]?.let {
                    if (it.highTemperatureNum.isEmpty() && it.lowTemperatureNum.isEmpty() && !it.singleTemp) {
                        updateStatusView(TEMP_NONE, 1)
                    } else if (it.singleTemp) {
                        targetNum.text = LocalDataDao.INSTANCE.formatHighValueUnit(it)

                        updateStatusView(TARGET_TEMP, 1)
                    } else {
                        targetNum.text = LocalDataDao.INSTANCE.formatHighValueUnit(it)
                        targetLowNum.text = LocalDataDao.INSTANCE.formatLowValueUnit(it)

                        updateStatusView(HIGH_LOW_TEMP, 1)
                    }
                    meatText.text = it.name
                    image1.setImageResource(it.iconRes)
                    profileArray[0] = it
                    mViewModel.setProfile(profileArray, mData.address, deviceType)
                }
            }
        })

        mDeviceStatusViewModel.profileData2.observeInFragment(this, Observer { item ->
            if (item.containsKey(mData.address)) {
                item[mData.address]?.let {
                    if (it.highTemperatureNum.isEmpty() && it.lowTemperatureNum.isEmpty() && !it.singleTemp) {
                        updateStatusView(TEMP_NONE, 2)
                    } else if (it.singleTemp) {
                        targetNum1.text = LocalDataDao.INSTANCE.formatHighValueUnit(it)

                        updateStatusView(TARGET_TEMP, 2)
                    } else {
                        targetNum1.text = LocalDataDao.INSTANCE.formatHighValueUnit(it)
                        targetLowNum1.text = LocalDataDao.INSTANCE.formatLowValueUnit(it)

                        updateStatusView(HIGH_LOW_TEMP, 2)
                    }
                    meatText1.text = it.name
                    image11.setImageResource(it.iconRes)
                    profileArray[1] = it
                    mViewModel.setProfile(profileArray, mData.address, deviceType)
                }
            }
        })

        mDeviceStatusViewModel.profileData3.observeInFragment(this, Observer { item ->
            if (item.containsKey(mData.address)) {
                item[mData.address]?.let {
                    if (it.highTemperatureNum.isEmpty() && it.lowTemperatureNum.isEmpty() && !it.singleTemp) {
                        updateStatusView(TEMP_NONE, 3)
                    } else if (it.singleTemp) {
                        targetNum2.text = LocalDataDao.INSTANCE.formatHighValueUnit(it)

                        updateStatusView(TARGET_TEMP, 3)
                    } else {
                        targetNum2.text = LocalDataDao.INSTANCE.formatHighValueUnit(it)
                        targetLowNum2.text = LocalDataDao.INSTANCE.formatLowValueUnit(it)

                        updateStatusView(HIGH_LOW_TEMP, 3)
                    }
                    meatText2.text = it.name
                    image12.setImageResource(it.iconRes)
                    profileArray[2] = it
                    mViewModel.setProfile(profileArray, mData.address, deviceType)
                }
            }
        })

        mDeviceStatusViewModel.profileData4.observeInFragment(this, Observer { item ->
            if (item.containsKey(mData.address)) {
                item[mData.address]?.let {
                    if (it.highTemperatureNum.isEmpty() && it.lowTemperatureNum.isEmpty() && !it.singleTemp) {
                        updateStatusView(TEMP_NONE, 4)
                    } else if (it.singleTemp) {
                        targetNum3.text = LocalDataDao.INSTANCE.formatHighValueUnit(it)

                        updateStatusView(TARGET_TEMP, 4)
                    } else {
                        targetNum3.text = LocalDataDao.INSTANCE.formatHighValueUnit(it)
                        targetLowNum3.text = LocalDataDao.INSTANCE.formatLowValueUnit(it)

                        updateStatusView(HIGH_LOW_TEMP, 4)
                    }
                    meatText3.text = it.name
                    image13.setImageResource(it.iconRes)
                    profileArray[3] = it
                    mViewModel.setProfile(profileArray, mData.address, deviceType)
                }
            }
        })

        mDeviceStatusViewModel.resetProfile.observeInFragment(this, Observer {
            mViewModel.setProfile(profileArray, mData.address, deviceType)
        })

        mDeviceStatusViewModel.profileListData.observeInFragment(this, Observer {
            println("=====> init profileListData $it")
            if (deviceType == DEVICE_TYPE_BBQ) {
                profileArray[0] = it[0]
                profileArray[1] = it[1]
                profileArray[2] = it[2]
                profileArray[3] = it[3]
            } else {
                profileArray[0] = it[0]
                profileArray[1] = it[1]
            }

            if (it[0].highTemperatureNum.isEmpty() && it[0].lowTemperatureNum.isEmpty()) {
                updateStatusView(TEMP_NONE, 1)
            } else if (it[0].singleTemp) {
                targetNum.text = LocalDataDao.INSTANCE.formatHighValueUnit(it[0])

                updateStatusView(TARGET_TEMP, 1)
            } else {
                targetNum.text = LocalDataDao.INSTANCE.formatHighValueUnit(it[0])
                targetLowNum.text = LocalDataDao.INSTANCE.formatLowValueUnit(it[0])

                updateStatusView(HIGH_LOW_TEMP, 1)
            }
            meatText.text = it[0].name
            image1.setImageResource(it[0].iconRes)

            if (it[1].highTemperatureNum.isEmpty() && it[1].lowTemperatureNum.isEmpty()) {
                updateStatusView(TEMP_NONE, 2)
            } else if (it[1].singleTemp) {
                targetNum1.text = LocalDataDao.INSTANCE.formatHighValueUnit(it[1])

                updateStatusView(TARGET_TEMP, 2)
            } else {
                targetNum1.text = LocalDataDao.INSTANCE.formatHighValueUnit(it[1])
                targetLowNum1.text = LocalDataDao.INSTANCE.formatLowValueUnit(it[1])

                updateStatusView(HIGH_LOW_TEMP, 2)
            }
            meatText1.text = it[1].name
            image11.setImageResource(it[1].iconRes)

            if (it.size() > 2) {
                if (it[2].highTemperatureNum.isEmpty() && it[2].lowTemperatureNum.isEmpty()) {
                    updateStatusView(TEMP_NONE, 3)
                } else if (it[2].singleTemp) {
                    targetNum2.text = LocalDataDao.INSTANCE.formatHighValueUnit(it[2])

                    updateStatusView(TARGET_TEMP, 3)
                } else {
                    targetNum2.text = LocalDataDao.INSTANCE.formatHighValueUnit(it[2])
                    targetLowNum2.text =
                        LocalDataDao.INSTANCE.formatLowValueUnit(it[2])

                    updateStatusView(HIGH_LOW_TEMP, 3)
                }
                meatText2.text = it[2].name
                image12.setImageResource(it[2].iconRes)

                if (it[3].highTemperatureNum.isEmpty() && it[3].lowTemperatureNum.isEmpty()) {
                    updateStatusView(TEMP_NONE, 4)
                } else if (it[3].singleTemp) {
                    targetNum3.text =
                        LocalDataDao.INSTANCE.formatHighValueUnit(it[3])

                    updateStatusView(TARGET_TEMP, 4)
                } else {
                    targetNum3.text =
                        LocalDataDao.INSTANCE.formatHighValueUnit(it[3])
                    targetLowNum3.text =
                        LocalDataDao.INSTANCE.formatLowValueUnit(it[3])

                    updateStatusView(HIGH_LOW_TEMP, 4)
                }
                meatText3.text = it[3].name
                image13.setImageResource(it[3].iconRes)
            }
            mBleViewModel.connectBluetooth(mData)
        })

        mDeviceStatusViewModel.alarmClock1.observeForever(Observer {
            if (it.containsKey(mData.address)) {
                mViewModel.alarmClockText1.postValue(hashMapOf<Long, EventAlarmTextData>().apply {
                    this[System.currentTimeMillis()] = EventAlarmTextData(
                        mData.address,
                        it[mData.address] ?: "0:0:0"
                    )
                })
            }

//            if (it.containsKey(mData.address)) {
//                if (it.values.last().isNotEmpty()) {
//                    val blockTimeText = it[mData.address] ?: "0:0:0"
//                    val h = blockTimeText.split(":")[0].toInt()
//                    val m = blockTimeText.split(":")[1].toInt()
//                    val s = blockTimeText.split(":")[2].toInt()
//                    if (h == 0 && m == 0 && s == 0) {
//                        textBlock1.text = ""
//                    } else {
//                        if (h == 0 && m == 0) {
//                            textBlock1.text = blockTimeText.split(":")[2]
//                        } else if (h == 0) {
//                            textBlock1.text =
//                                blockTimeText.split(":")[1] + ":" + blockTimeText.split(":")[2]
//                        } else {
//                            textBlock1.text = blockTimeText
//                        }
//                    }
//                } else {
//                    textBlock1.text = ""
//                }
//            }
        })

        mViewModel.alarmClockText1.observeInFragment(this, Observer {
            val alarmData = it.values.last()
            if (alarmData.address == mData.address) {
                if (alarmData.alarmText.isNotEmpty() && alarmData.alarmText.contains(":")) {
                    val blockTimeText = alarmData.alarmText
                    val h = blockTimeText.split(":")[0].toInt()
                    val m = blockTimeText.split(":")[1].toInt()
                    val s = blockTimeText.split(":")[2].toInt()
                    if (h == 0 && m == 0 && s == 0) {
                        textBlock1.text = ""
                    } else {
                        if (h == 0 && m == 0) {
                            textBlock1.text = blockTimeText.split(":")[2]
                        } else if (h == 0) {
                            textBlock1.text =
                                blockTimeText.split(":")[1] + ":" + blockTimeText.split(":")[2]
                        } else {
                            textBlock1.text = blockTimeText
                        }
                    }
                } else {
                    textBlock1.text = ""
                }
            }
        })

        mViewModel.alarmClockText2.observeInFragment(this, Observer {
            val alarmData = it.values.last()
            if (alarmData.address == mData.address) {
                if (alarmData.alarmText.isNotEmpty() && alarmData.alarmText.contains(":")) {
                    val blockTimeText = alarmData.alarmText
                    val h = blockTimeText.split(":")[0].toInt()
                    val m = blockTimeText.split(":")[1].toInt()
                    val s = blockTimeText.split(":")[2].toInt()
                    if (h == 0 && m == 0 && s == 0) {
                        textBlock2.text = ""
                    } else {
                        if (h == 0 && m == 0) {
                            textBlock2.text = blockTimeText.split(":")[2]
                        } else if (h == 0) {
                            textBlock2.text =
                                blockTimeText.split(":")[1] + ":" + blockTimeText.split(":")[2]
                        } else {
                            textBlock2.text = blockTimeText
                        }
                    }
                } else {
                    textBlock2.text = ""
                }
            }
        })

        mDeviceStatusViewModel.alarmClock2.observeForever(Observer {
            if (it.containsKey(mData.address)) {
                mViewModel.alarmClockText2.postValue(hashMapOf<Long, EventAlarmTextData>().apply {
                    this[System.currentTimeMillis()] = EventAlarmTextData(
                        mData.address,
                        it[mData.address] ?: "0:0:0"
                    )
                })
            }
        })

        mViewModel.alarmClockText3.observeInFragment(this, Observer {
            val alarmData = it.values.last()
            if (alarmData.address == mData.address) {
                if (alarmData.alarmText.isNotEmpty() && alarmData.alarmText.contains(":")) {
                    val blockTimeText = alarmData.alarmText
                    val h = blockTimeText.split(":")[0].toInt()
                    val m = blockTimeText.split(":")[1].toInt()
                    val s = blockTimeText.split(":")[2].toInt()
                    if (h == 0 && m == 0 && s == 0) {
                        textBlock3.text = ""
                    } else {
                        if (h == 0 && m == 0) {
                            textBlock3.text = blockTimeText.split(":")[2]
                        } else if (h == 0) {
                            textBlock3.text =
                                blockTimeText.split(":")[1] + ":" + blockTimeText.split(":")[2]
                        } else {
                            textBlock3.text = blockTimeText
                        }
                    }
                } else {
                    textBlock3.text = ""
                }
            }
        })

        mDeviceStatusViewModel.alarmClock3.observeForever(Observer {
            if (it.containsKey(mData.address)) {
                if (it.containsKey(mData.address)) {
                    mViewModel.alarmClockText3.postValue(hashMapOf<Long, EventAlarmTextData>().apply {
                        this[System.currentTimeMillis()] = EventAlarmTextData(
                            mData.address,
                            it[mData.address] ?: "0:0:0"
                        )
                    })
                }
            }
        })

        mViewModel.alarmClockText4.observeInFragment(this, Observer {
            val alarmData = it.values.last()
            if (alarmData.address == mData.address) {
                if (alarmData.alarmText.isNotEmpty() && alarmData.alarmText.contains(":")) {
                    val blockTimeText = alarmData.alarmText
                    val h = blockTimeText.split(":")[0].toInt()
                    val m = blockTimeText.split(":")[1].toInt()
                    val s = blockTimeText.split(":")[2].toInt()
                    if (h == 0 && m == 0 && s == 0) {
                        textBlock4.text = ""
                    } else {
                        if (h == 0 && m == 0) {
                            textBlock4.text = blockTimeText.split(":")[2]
                        } else if (h == 0) {
                            textBlock4.text =
                                blockTimeText.split(":")[1] + ":" + blockTimeText.split(":")[2]
                        } else {
                            textBlock4.text = blockTimeText
                        }
                    }
                } else {
                    textBlock4.text = ""
                }
            }
        })

        mDeviceStatusViewModel.alarmClock4.observeForever(Observer {
            if (it.containsKey(mData.address)) {
                if (it.containsKey(mData.address)) {
                    mViewModel.alarmClockText4.postValue(hashMapOf<Long, EventAlarmTextData>().apply {
                        this[System.currentTimeMillis()] = EventAlarmTextData(
                            mData.address,
                            it[mData.address] ?: "0:0:0"
                        )
                    })
                }
            }
        })

        mEventViewModel.refreshTempUnit.observeInFragment(this, Observer {
            if (profileArray.isNotEmpty()) {
                if (profileArray[0] != null) {
                    targetNum.text = LocalDataDao.INSTANCE.formatHighValueUnit(profileArray[0])
                    targetLowNum.text = LocalDataDao.INSTANCE.formatLowValueUnit(profileArray[0])
                }
                if (profileArray[1] != null) {
                    targetNum1.text = LocalDataDao.INSTANCE.formatHighValueUnit(profileArray[1])
                    targetLowNum1.text = LocalDataDao.INSTANCE.formatLowValueUnit(profileArray[1])
                }
                if (profileArray[2] != null) {
                    targetNum2.text = LocalDataDao.INSTANCE.formatHighValueUnit(profileArray[2])
                    targetLowNum2.text = LocalDataDao.INSTANCE.formatLowValueUnit(profileArray[2])
                }
                if (profileArray[3] != null) {
                    targetNum3.text = LocalDataDao.INSTANCE.formatHighValueUnit(profileArray[3])
                    targetLowNum3.text = LocalDataDao.INSTANCE.formatLowValueUnit(profileArray[3])
                }
            }

            if (probeArray.isNotEmpty()) {
                viewNum.text = LocalDataDao.INSTANCE.convertUnitNum(probeArray[0].temperatureNUm)
                viewNum1.text = LocalDataDao.INSTANCE.convertUnitNum(probeArray[1].temperatureNUm)
                viewNum2.text = LocalDataDao.INSTANCE.convertUnitNum(probeArray[2].temperatureNUm)
                viewNum3.text = LocalDataDao.INSTANCE.convertUnitNum(probeArray[3].temperatureNUm)

                viewUnit.text = LocalDataDao.INSTANCE.getTempUnit()
                viewUnit1.text = LocalDataDao.INSTANCE.getTempUnit()
                viewUnit2.text = LocalDataDao.INSTANCE.getTempUnit()
                viewUnit3.text = LocalDataDao.INSTANCE.getTempUnit()
            }
        })

        mBleViewModel.probeTempComputeTime.observeForever(Observer {
            mViewModel.compute2TempTime.postValue(it.second)
            //剩余时间倒计时
            val address = it.second.keys.last().split("_")[0]
            if (mData.address == address) {
                val clockIndex = it.second.keys.last().split("_")[1].toIntOrNull() ?: -1
                if (it.second.values.last().split(":").size > 2) {
                    println("123->  mDeviceStatusViewModel  bbq  startTimeClock ")
                    mDeviceStatusViewModel.startTimeClock(
                        address,
                        clockIndex,
                        it.second.values.last()
                    )
                } else {
                    if (mDeviceStatusViewModel.isBlockTimeWorking(clockIndex, address)) {
                        mDeviceStatusViewModel.resetBlockTimeWorking(clockIndex, address)
                    }
                }
            }
        })

        mViewModel.compute2TempTime.observeInFragment(this, Observer {
            if (it.isNotEmpty()) {
                it.keys.forEach { itKey ->
                    val address = itKey.split("_")[0]
                    if (mData.address == address) {
                        val forecastTime = it[itKey].orEmpty() ?: ""
                        when (itKey.split("_")[1].toIntOrNull()) {
                            0 -> {
                                viewForecastTime.text = LocalDataDao.INSTANCE.formatNeedTime(forecastTime)
                            }
                            1 -> {
                                viewForecastTime1.text = LocalDataDao.INSTANCE.formatNeedTime(forecastTime)
                            }
                            2 -> {
                                viewForecastTime2.text = LocalDataDao.INSTANCE.formatNeedTime(forecastTime)
                            }
                            3 -> {
                                viewForecastTime3.text = LocalDataDao.INSTANCE.formatNeedTime(forecastTime)
                            }
                            else -> {

                            }
                        }
                    }
                }
            }
        })

        mDeviceStatusViewModel.needTimeClock1.observeInFragment(this, Observer {
            if (it.containsKey(mData.address)) {
                if (it.values.last().isNotEmpty()) {
                    val blockTimeText = it[mData.address] ?: ""
//                    val h = blockTimeText.split(":")[0].toInt()
//                    val m = blockTimeText.split(":")[1].toInt()
//                    val s = blockTimeText.split(":")[2].toInt()
//                    if (h == 0 && m == 0 && s == 0) {
//                        viewForecastTime.text = ""
//                    } else {
//                        if (h == 0 && m == 0) {
//                            viewForecastTime.text = blockTimeText.split(":")[2]
//                        } else if (h == 0) {
//                            viewForecastTime.text =
//                                blockTimeText.split(":")[1] + ":" + blockTimeText.split(":")[2]
//                        } else {
//                            viewForecastTime.text = blockTimeText
//                        }
//                    }
                    viewForecastTime.text = LocalDataDao.INSTANCE.formatNeedTime(blockTimeText)
                } else {
                    viewForecastTime.text =  LocalDataDao.INSTANCE.formatNeedTime()
                }
            }
        })

        mDeviceStatusViewModel.needTimeClock2.observeInFragment(this, Observer {
            if (it.containsKey(mData.address)) {
                if (it.values.last().isNotEmpty()) {
                    val blockTimeText = it[mData.address] ?: ""

                    viewForecastTime1.text = LocalDataDao.INSTANCE.formatNeedTime(blockTimeText)
                } else {
                    viewForecastTime1.text = LocalDataDao.INSTANCE.formatNeedTime()
                }
            }
        })

        mDeviceStatusViewModel.needTimeClock3.observeInFragment(this, Observer {
            if (it.containsKey(mData.address)) {
                if (it.values.last().isNotEmpty()) {
                    val blockTimeText = it[mData.address] ?: ""

                    viewForecastTime2.text = LocalDataDao.INSTANCE.formatNeedTime(blockTimeText)
                } else {
                    viewForecastTime2.text =  LocalDataDao.INSTANCE.formatNeedTime()
                }
            }
        })

        mDeviceStatusViewModel.needTimeClock4.observeInFragment(this, Observer {
            if (it.containsKey(mData.address)) {
                if (it.values.last().isNotEmpty()) {
                    val blockTimeText = it[mData.address] ?: ""

                    viewForecastTime3.text = LocalDataDao.INSTANCE.formatNeedTime(blockTimeText)
                } else {
                    viewForecastTime3.text =  LocalDataDao.INSTANCE.formatNeedTime()
                }
            }
        })
    }

    /**
     * 更新温度等状态
     */
    private fun updateTemp(itList: MutableList<ProbeBean>) {
        probeArray.clear()
        probeArray.addAll(itList)
        if (itList.size == 2) {
            viewNum.text = LocalDataDao.INSTANCE.convertUnitNum(itList[0].temperatureNUm)
            viewUnit.text = LocalDataDao.INSTANCE.getTempUnit()
            viewNum1.text = LocalDataDao.INSTANCE.convertUnitNum(itList[1].temperatureNUm)
            viewUnit1.text = LocalDataDao.INSTANCE.getTempUnit()
            if (itList[0].temperatureNUm.isNotEmpty()) {
                viewNoData.isVisible = false
                flow2.isInvisible = false
            } else {
                viewNoData.isVisible = true
                flow2.isInvisible = true
            }
            if (itList[1].temperatureNUm.isNotEmpty()) {
                viewNoData1.isVisible = false
                flow21.isInvisible = false
            } else {
                viewNoData1.isVisible = true
                flow21.isInvisible = true
            }
        } else if (itList.size == 4) {
            viewNum.text = LocalDataDao.INSTANCE.convertUnitNum(itList[0].temperatureNUm)
            viewNum1.text = LocalDataDao.INSTANCE.convertUnitNum(itList[1].temperatureNUm)
            viewNum2.text = LocalDataDao.INSTANCE.convertUnitNum(itList[2].temperatureNUm)
            viewNum3.text = LocalDataDao.INSTANCE.convertUnitNum(itList[3].temperatureNUm)

            viewUnit.text = LocalDataDao.INSTANCE.getTempUnit()
            viewUnit1.text = LocalDataDao.INSTANCE.getTempUnit()
            viewUnit2.text = LocalDataDao.INSTANCE.getTempUnit()
            viewUnit3.text = LocalDataDao.INSTANCE.getTempUnit()
            if (itList[0].temperatureNUm.isNotEmpty()) {
                viewNoData.isVisible = false
                flow2.isInvisible = false
            } else {
                viewNoData.isVisible = true
                flow2.isInvisible = true
            }
            if (itList[1].temperatureNUm.isNotEmpty()) {
                viewNoData1.isVisible = false
                flow21.isInvisible = false
            } else {
                viewNoData1.isVisible = true
                flow21.isInvisible = true
            }
            if (itList[2].temperatureNUm.isNotEmpty()) {
                viewNoData2.isVisible = false
                flow22.isInvisible = false
            } else {
                viewNoData2.isVisible = true
                flow22.isInvisible = true
            }
            if (itList[3].temperatureNUm.isNotEmpty()) {
                viewNoData3.isVisible = false
                flow23.isInvisible = false
            } else {
                viewNoData3.isVisible = true
                flow23.isInvisible = true
            }
        }
        setBatteryLevel(itList.last().batteryNum.toIntOrNull() ?: -1)
    }

    private fun setSignal(level: Int) {
        when (level) {
            in -100..-90 -> {
                viewPhoneBBQ.setImageResource(R.drawable.main_not_connected)
            }
            in -90..-80 -> {
                viewPhoneBBQ.setImageResource(R.drawable.signal_weak)
            }
            in -80..-70 -> {
                viewPhoneBBQ.setImageResource(R.drawable.signal_mid2)
            }
            in -70..-60 -> {
                viewPhoneBBQ.setImageResource(R.drawable.signal_mid1)
            }
            in -60..-50 -> {
                viewPhoneBBQ.setImageResource(R.drawable.signal_strong2)
            }
            in -50..0 -> {
                viewPhoneBBQ.setImageResource(R.drawable.signal_strong1)
            }
        }
    }

    private fun setBatteryLevel(level: Int) {
        when (level) {
            in 0..1 -> {
                viewBattery.setImageResource(R.drawable.battery_null)
            }
            in 2..4 -> {
                viewBattery.setImageResource(R.drawable.battery_low)
            }
            in 5..7 -> {
                viewBattery.setImageResource(R.drawable.battery_mid)
            }
            in 8..9 -> {
                viewBattery.setImageResource(R.drawable.battery_full)
            }
            else -> viewBattery.setImageResource(R.drawable.battery_full)
        }
    }


    private fun updateStatusView(status: Int, viewPosition: Int) {
        when (status) {
            TARGET_TEMP -> {
                when (viewPosition) {
                    1 -> {
                        image2.isInvisible = false
                        targetNum.isInvisible = false
                        image3.isInvisible = true
                        targetLowNum.isInvisible = true
                        textTarget.isInvisible = false
                    }
                    2 -> {
                        image21.isInvisible = false
                        targetNum1.isInvisible = false
                        image31.isInvisible = true
                        targetLowNum1.isInvisible = true
                        textTarget1.isInvisible = false
                    }
                    3 -> {
                        image22.isInvisible = false
                        targetNum2.isInvisible = false
                        image32.isInvisible = true
                        targetLowNum2.isInvisible = true
                        textTarget2.isInvisible = false
                    }
                    4 -> {
                        image23.isInvisible = false
                        targetNum3.isInvisible = false
                        image33.isInvisible = true
                        targetLowNum3.isInvisible = true
                        textTarget3.isInvisible = false
                    }
                }
            }
            HIGH_LOW_TEMP -> {
                when (viewPosition) {
                    1 -> {
                        image2.isInvisible = false
                        targetNum.isInvisible = false
                        image3.isInvisible = false
                        targetLowNum.isInvisible = false
                        textTarget.isInvisible = true
                    }
                    2 -> {
                        image21.isInvisible = false
                        targetNum1.isInvisible = false
                        image31.isInvisible = false
                        targetLowNum1.isInvisible = false
                        textTarget1.isInvisible = true
                    }
                    3 -> {
                        image22.isInvisible = false
                        targetNum2.isInvisible = false
                        image32.isInvisible = false
                        targetLowNum2.isInvisible = false
                        textTarget2.isInvisible = true
                    }
                    4 -> {
                        image23.isInvisible = false
                        targetNum3.isInvisible = false
                        image33.isInvisible = false
                        targetLowNum3.isInvisible = false
                        textTarget3.isInvisible = true
                    }
                }
            }
            TEMP_NONE -> {
                when (viewPosition) {
                    1 -> {
                        image2.isInvisible = true
                        targetNum.isInvisible = true
                        image3.isInvisible = true
                        targetLowNum.isInvisible = true
                        textTarget.isInvisible = true
                    }
                    2 -> {
                        image21.isInvisible = true
                        targetNum1.isInvisible = true
                        image31.isInvisible = true
                        targetLowNum1.isInvisible = true
                        textTarget1.isInvisible = true
                    }
                    3 -> {
                        image22.isInvisible = true
                        targetNum2.isInvisible = true
                        image32.isInvisible = true
                        targetLowNum2.isInvisible = true
                        textTarget2.isInvisible = true
                    }
                    4 -> {
                        image23.isInvisible = true
                        targetNum3.isInvisible = true
                        image33.isInvisible = true
                        targetLowNum3.isInvisible = true
                        textTarget3.isInvisible = true
                    }
                }
            }
        }
    }

    private fun setListener() {
        viewNum.typeface = AppContext.get().getTypeFace()
        viewNum1.typeface = AppContext.get().getTypeFace()
        viewNum2.typeface = AppContext.get().getTypeFace()
        viewNum3.typeface = AppContext.get().getTypeFace()

        backButton.setOnClickListener {
            requireActivity().onBackPressed()
        }

        mainMenuButton.setOnClickListener {
            parentFragmentManager.beginTransaction()
                .setCustomAnimations(
                    R.anim.translate_into, R.anim.translate_out,
                    R.anim.translate_into_pop, R.anim.translate_out_exit
                )
                .add(
                    R.id.mainContent,
                    BBQSettingFragment.newInstance(mData.address, deviceType)
                )
                .addToBackStack("main")
                .commit()
        }

        flow1.setOnClickListener {
            parentFragmentManager.beginTransaction()
                .setCustomAnimations(
                    R.anim.translate_into, R.anim.translate_out,
                    R.anim.translate_into_pop, R.anim.translate_out_exit
                )
                .add(
                    R.id.mainContent,
                    SetProfileFragment.newInstance(
                        1, meatText.text.toString(),
                        DEVICE_TYPE_BBQ, mData.address
                    )
                )
                .addToBackStack("main")
                .commit()
        }

        flow11.setOnClickListener {
            parentFragmentManager.beginTransaction()
                .setCustomAnimations(
                    R.anim.translate_into, R.anim.translate_out,
                    R.anim.translate_into_pop, R.anim.translate_out_exit
                )
                .add(
                    R.id.mainContent,
                    SetProfileFragment.newInstance(
                        2, meatText1.text.toString(),
                        DEVICE_TYPE_BBQ, mData.address
                    )
                )
                .addToBackStack("main")
                .commit()
        }

        flow12.setOnClickListener {
            parentFragmentManager.beginTransaction()
                .setCustomAnimations(
                    R.anim.translate_into, R.anim.translate_out,
                    R.anim.translate_into_pop, R.anim.translate_out_exit
                )
                .add(
                    R.id.mainContent,
                    SetProfileFragment.newInstance(
                        3, meatText2.text.toString(),
                        DEVICE_TYPE_BBQ, mData.address
                    )
                )
                .addToBackStack("main")
                .commit()
        }

        flow13.setOnClickListener {
            parentFragmentManager.beginTransaction()
                .setCustomAnimations(
                    R.anim.translate_into, R.anim.translate_out,
                    R.anim.translate_into_pop, R.anim.translate_out_exit
                )
                .add(
                    R.id.mainContent,
                    SetProfileFragment.newInstance(
                        4, meatText3.text.toString(),
                        DEVICE_TYPE_BBQ, mData.address
                    )
                )
                .addToBackStack("main")
                .commit()
        }

        viewTime1.setOnClickListener {
//            val lineRegression= MyLineRegression()
//            lineRegression.test()
            parentFragmentManager.beginTransaction()
                .setCustomAnimations(
                    R.anim.translate_into, R.anim.translate_out,
                    R.anim.translate_into_pop, R.anim.translate_out_exit
                )
                .add(
                    R.id.mainContent,
                    BlockTimerFragment.newInstance(0, mData.address)
                )
                .addToBackStack("main")
                .commit()
        }

        viewTime11.setOnClickListener {
            parentFragmentManager.beginTransaction()
                .setCustomAnimations(
                    R.anim.translate_into, R.anim.translate_out,
                    R.anim.translate_into_pop, R.anim.translate_out_exit
                )
                .add(
                    R.id.mainContent,
                    BlockTimerFragment.newInstance(1, mData.address)
                )
                .addToBackStack("main")
                .commit()
        }

        viewTime12.setOnClickListener {
            parentFragmentManager.beginTransaction()
                .setCustomAnimations(
                    R.anim.translate_into, R.anim.translate_out,
                    R.anim.translate_into_pop, R.anim.translate_out_exit
                )
                .add(
                    R.id.mainContent,
                    BlockTimerFragment.newInstance(2, mData.address)
                )
                .addToBackStack("main")
                .commit()
        }

        viewTime13.setOnClickListener {
            parentFragmentManager.beginTransaction()
                .setCustomAnimations(
                    R.anim.translate_into, R.anim.translate_out,
                    R.anim.translate_into_pop, R.anim.translate_out_exit
                )
                .add(
                    R.id.mainContent,
                    BlockTimerFragment.newInstance(3, mData.address)
                )
                .addToBackStack("main")
                .commit()
        }

        viewTrend1.setOnClickListener {
            val tempNumList = arrayListOf<String>()
            probeArray.forEach {
                tempNumList.add(it.temperatureNUm)
            }
            if (tempNumList.isEmpty()) {
                if (mData.name.contains("grill", true)) {
                    tempNumList.add("")
                    tempNumList.add("")
                } else {
                    tempNumList.add("")
                    tempNumList.add("")
                    tempNumList.add("")
                    tempNumList.add("")
                }
            }
            parentFragmentManager.beginTransaction()
                .setCustomAnimations(
                    R.anim.translate_into, R.anim.translate_out,
                    R.anim.translate_into_pop, R.anim.translate_out_exit
                )
                .add(
                    R.id.mainContent,
                    TempGraphFragment.newInstance(tempNumList, 0, deviceType, mData.address)
                )
                .addToBackStack("main")
                .commit()
        }

        viewTrend11.setOnClickListener {
            val tempNumList = arrayListOf<String>()
            probeArray.forEach {
                tempNumList.add(it.temperatureNUm)
            }
            if (tempNumList.isEmpty()) {
                if (mData.name.contains("grill", true)) {
                    tempNumList.add("")
                    tempNumList.add("")
                } else {
                    tempNumList.add("")
                    tempNumList.add("")
                    tempNumList.add("")
                    tempNumList.add("")
                }
            }
            parentFragmentManager.beginTransaction()
                .setCustomAnimations(
                    R.anim.translate_into, R.anim.translate_out,
                    R.anim.translate_into_pop, R.anim.translate_out_exit
                )
                .add(
                    R.id.mainContent,
                    TempGraphFragment.newInstance(tempNumList, 1, deviceType, mData.address)
                )
                .addToBackStack("main")
                .commit()
        }

        viewTrend12.setOnClickListener {
            val tempNumList = arrayListOf<String>()
            probeArray.forEach {
                tempNumList.add(it.temperatureNUm)
            }
            if (tempNumList.isEmpty()) {
                tempNumList.add("")
                tempNumList.add("")
                tempNumList.add("")
                tempNumList.add("")
            }
            parentFragmentManager.beginTransaction()
                .setCustomAnimations(
                    R.anim.translate_into, R.anim.translate_out,
                    R.anim.translate_into_pop, R.anim.translate_out_exit
                )
                .add(
                    R.id.mainContent,
                    TempGraphFragment.newInstance(tempNumList, 2, deviceType, mData.address)
                )
                .addToBackStack("main")
                .commit()
        }

        viewTrend13.setOnClickListener {
            val tempNumList = arrayListOf<String>()
            probeArray.forEach {
                tempNumList.add(it.temperatureNUm)
            }
            if (tempNumList.isEmpty()) {
                tempNumList.add("")
                tempNumList.add("")
                tempNumList.add("")
                tempNumList.add("")
            }
            parentFragmentManager.beginTransaction()
                .setCustomAnimations(
                    R.anim.translate_into, R.anim.translate_out,
                    R.anim.translate_into_pop, R.anim.translate_out_exit
                )
                .add(
                    R.id.mainContent,
                    TempGraphFragment.newInstance(tempNumList, 3, deviceType, mData.address)
                )
                .addToBackStack("main")
                .commit()
        }

    }
}